package com.gdth.bank.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdth.bank.R;
import com.gdth.bank.adapter.DzCpKhListViewAdapter;
import com.gdth.bank.bean.DzCpItem;
import com.gdth.bank.presenter.DzCpKhXxEtcPresenter;
import com.gdth.bank.presenter.DzCpKhXxPosPresenter;
import com.gdth.bank.utils.ServerUtil;
import com.gdth.bank.view.DzCpKhXxEtcView;
import com.gdth.bank.view.DzCpKhXxPosView;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.database.bean.DzCpkhXxDjEtc;
import com.gdth.database.bean.DzCpkhXxDjPos;
import com.gdth.database.bean.TXtBm;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.Mode;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.gdth.widget.pulltorefresh.library.PullToRefreshListView;

public class DzCpKhXxListActivity extends BaseActivity implements
		DzCpKhXxEtcView, DzCpKhXxPosView {
	@ViewInject(id = R.id.header_label_title)
	TextView txt_header_title;
	@ViewInject(id = R.id.header_btn_left, click = "finishClick")
	TextView txt_header_left;
	@ViewInject(id = R.id.header_btn_right, click = "addClick")
	TextView txt_header_right;
	@ViewInject(id = R.id.dzcpkhxx_query, click = "queryClick")
	TextView txt_query;
	@ViewInject(id = R.id.dzcp_editTextNote)
	EditText edit_query;
	@ViewInject(id = R.id.listView)
	PullToRefreshListView listView;
	ListView mListView;
	List<DzCpItem> listData;
	DzCpKhListViewAdapter mAdapter;
	/** 提示框 */
	ProgressDialog mProgressDialog;
	DzCpKhXxEtcPresenter mDzCpKhXxEtcPresenter;
	DzCpKhXxPosPresenter mDzCpKhXxPosPresenter;
	List<DzCpkhXxDjEtc> dzcpkhxxetcList;
	List<DzCpkhXxDjPos> dzcpkhxxposList;
	String val;
	DzCpItem gbsj;
	int positions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dzcpkhxxdjl_list);
		initView();
		init();

	}

	@SuppressLint("ResourceAsColor")
	private void initView() {
		txt_header_title.setText(getResources().getString(R.string.param150));
		mProgressDialog = new ProgressDialog(this);
		gbsj = new DzCpItem();
		mListView = listView.getRefreshableView();
		mListView.setDivider(new ColorDrawable(R.color.line_color));
		mListView.setDividerHeight(1);
		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
				/*
				 * Toast.makeText(DzCpKhXxListActivity.this, "最后一个",
				 * Toast.LENGTH_SHORT).show();
				 */
			}
		});

		listData = new ArrayList<DzCpItem>();

		mAdapter = new DzCpKhListViewAdapter(this, listData);

		listView.setAdapter(mAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				/*
				 * BaseToast.getInstance().ShowSystemToast(DzCpKhXxDjListActivity
				 * .this, "");
				 */
				int po = position - 1;
				DzCpItem item = listData.get(po);
				String appuuid = item.getKey();
				int type = item.getType();
				Long idKey = item.getIdKey();
				/* String zt=item.getZt(); */
				if (type == 0) {
					Intent intent = new Intent();
					intent.setClass(DzCpKhXxListActivity.this,
							DzCpKhXxEtcActivity.class);
					intent.putExtra("appuuid", appuuid);
					intent.putExtra("type", type);
					intent.putExtra("scbs", "1");
					intent.putExtra("idKey", idKey);
					intent.putExtra("po", String.valueOf(po));
					startActivityForResult(intent, 0);
					// startActivity(intent);

				} else {
					Intent intent = new Intent();
					intent.setClass(DzCpKhXxListActivity.this,
							DzCpKhXxPosActivity.class);
					intent.putExtra("appuuid", appuuid);
					intent.putExtra("type", type);
					intent.putExtra("idKey", idKey);
					intent.putExtra("scbs", "1");
					intent.putExtra("po", String.valueOf(po));
					/* startActivity(intent); */
					startActivityForResult(intent, 0);
				}

			}
		});

		listView.setMode(Mode.DISABLED);

		registerForContextMenu(mListView);
	}

	private void init() {
		listData.clear();
		mDzCpKhXxEtcPresenter = new DzCpKhXxEtcPresenter(this);
		mDzCpKhXxEtcPresenter.getAllDzcpkhxxetc("");
		mDzCpKhXxPosPresenter = new DzCpKhXxPosPresenter(this);

	}

	@Override
	public void showProgressDialog(String msg) {
		// TODO Auto-generated method stub
		mProgressDialog.setMessage(msg);
		mProgressDialog.show();
	}

	@Override
	public void hideProgressDialog() {
		// TODO Auto-generated method stub
		mProgressDialog.hide();
	}

	@Override
	public void showMessage(String msg) {
		// TODO Auto-generated method stub
		/* BaseToast.getInstance().ShowSystemToast(this, msg); */
		Toast.makeText(DzCpKhXxListActivity.this, msg, Toast.LENGTH_SHORT)
				.show();
	}

	@Override
	public void updateView(int type, Object Obj) {
		// TODO Auto-generated method stub
		if (type == ServerUtil.server_save) {
			showMessage(getResources().getString(R.string.param155));
		} else if (type == ServerUtil.server_delete) {
			showMessage(getResources().getString(R.string.param156));
			mAdapter.notifyDataSetChanged();
		}

	}

	@Override
	public void updateList(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub
		dzcpkhxxetcList = mList;
		for (DzCpkhXxDjEtc mdzcpkhxxlList : mList) {
			DzCpItem mImageItem = new DzCpItem();
			mImageItem.setIdKey(mdzcpkhxxlList.getId());
			mImageItem.setKey(mdzcpkhxxlList.getAppUuid());
			mImageItem.setValue(mdzcpkhxxlList.getKhMc());
			mImageItem.setSfz(mdzcpkhxxlList.getKhZjh());
			mImageItem.setType(0);
			mImageItem.setLx("ETC");
			int sbzt = mdzcpkhxxlList.getXgzt();
			/*
			 * if(sbzt==0){ mImageItem.setZt("未上传"); }
			 */
			mImageItem.setImg("ETC");
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(mdzcpkhxxlList.getSqSj());
			mImageItem.setDate(dateString);
			String[] str = dateString.split(" ");
			mImageItem.setXsSj(str[0]);
			listData.add(mImageItem);
		}
		if (val != null) {
			mDzCpKhXxPosPresenter.getAllDzcpkhxxpos(val);
		} else {
			mDzCpKhXxPosPresenter.getAllDzcpkhxxpos("");
		}
		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();
		showMessage(getResources().getString(R.string.param157));

	}

	public void addClick(View arg0) {
		/*
		 * DialogList dialog=new DialogList(this, "电子产品", false); List<Item>
		 * items = new ArrayList<Item>(); Item item1=new Item();
		 * item1.setValue("ETC");
		 * item1.setKey("com.gdth.bank.activity.DzCpKhXxEtcActivity");
		 * items.add(item1); Item item2=new Item(); item2.setValue("POS");
		 * item2.setKey("com.gdth.bank.activity.DzCpKhXxPosActivity");
		 * items.add(item2); dialog.setListItem(items); dialog.show();
		 */

	}

	public void queryClick(View arg0) {
		query();
	}

	private void query() {
		listData.clear();
		val = edit_query.getText().toString();
		mDzCpKhXxEtcPresenter.getAllDzcpkhxxetc(val);

	}

	@Override
	public void updateViewpos(int type, Object Obj) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateListpos(List<DzCpkhXxDjPos> mList) {
		// TODO Auto-generated method stub
		dzcpkhxxposList = mList;
		for (DzCpkhXxDjPos mdzcpkhxxposlList : mList) {
			DzCpItem mImageItem = new DzCpItem();
			mImageItem.setIdKey(mdzcpkhxxposlList.getId());
			mImageItem.setKey(mdzcpkhxxposlList.getAppUuid());
			mImageItem.setValue(mdzcpkhxxposlList.getKhMc());
			mImageItem.setSfz(mdzcpkhxxposlList.getKhZjh());
			mImageItem.setType(1);
			mImageItem.setLx("POS");
			/*
			 * if(mdzcpkhxxposlList.getXgzt()==0){ mImageItem.setZt("未上传"); }
			 */
			mImageItem.setImg("POS");
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(mdzcpkhxxposlList.getSqSj());
			mImageItem.setDate(dateString);
			String[] str = dateString.split(" ");
			mImageItem.setXsSj(str[0]);
			listData.add(mImageItem);
		}
		Collections.sort(listData, new Comparator<DzCpItem>() {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			private Date getDate(DzCpItem m) {
				if (m == null || m.getDate() == null)
					return null;
				try {
					return sdf.parse(m.getDate());
				} catch (ParseException e) {
					return null;
				}
			}

			@Override
			public int compare(DzCpItem lhs, DzCpItem rhs) {
				// TODO Auto-generated method stub
				Date d1 = getDate(lhs);
				Date d2 = getDate(rhs);
				if (d1 == null && d2 == null)
					return 0;

				if (d1 == null)
					return -1;
				if (d2 == null)
					return 1;
				return d2.compareTo(d1);
			}
		});

		listView.onRefreshComplete();
		mAdapter.notifyDataSetChanged();

		showMessage(getResources().getString(R.string.param158));

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.setHeaderTitle(getResources().getString(R.string.param159));
		menu.add(0, 1, Menu.NONE, getResources().getString(R.string.param160));
		menu.add(0, 2, Menu.NONE, getResources().getString(R.string.param161));

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// 得到当前被选中的item信息
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int position = menuInfo.position;

		switch (item.getItemId()) {
		case 1:
			upload(position);
			break;
		case 2:
			delete(position);
			break;
		default:
			return super.onContextItemSelected(item);
		}
		return true;
	}

	@Override
	public void updateListUp(List<DzCpkhXxDjEtc> mList) {
		// TODO Auto-generated method stub

	}

	@Override
	public void success() {
		// TODO Auto-generated method stub
		/*
		 * listData.clear(); mDzCpKhXxEtcPresenter =new
		 * DzCpKhXxEtcPresenter(this);
		 * mDzCpKhXxEtcPresenter.getAllDzcpkhxxetc("");
		 */
		listData.remove(positions - 1);
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void updateListBm(List<TXtBm> mList) {
		// TODO Auto-generated method stub

	}

	private void upload(int position) {
		positions = position;
		gbsj = listData.get(position - 1);
		String appuuid = gbsj.getKey();
		int type = gbsj.getType();
		if (type == 0) {
			mDzCpKhXxEtcPresenter.uploadDzcpkhxxetc(appuuid);

		} else {
			mDzCpKhXxPosPresenter.uploadDzcpkhxxpos(appuuid);
		}
		mAdapter.notifyDataSetChanged();
	}

	private void delete(int position) {
		DzCpItem item = listData.get(position - 1);
		int type = item.getType();
		if (type == 0) {
			String appuuid = item.getKey();
			mDzCpKhXxEtcPresenter.deleteDzcpkhxxetc(appuuid);
			listData.remove(position - 1);
		} else {
			String appuuid = item.getKey();
			mDzCpKhXxPosPresenter.deleteDzcpkhxxpos(appuuid);
			listData.remove(position - 1);
		}
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case RESULT_OK:
			String result = data.getStringExtra("po");
			listData.remove(Integer.parseInt(result));
			mAdapter.notifyDataSetChanged();
		default:
			break;
		}

	}

	@Override
	public void scsuccess() {
		// TODO Auto-generated method stub
		listData.remove(positions - 1);
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void AlertDialog() {
		// TODO Auto-generated method stub

	}

	@Override
	public void jyZhj(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void refreshData(List<DzCpkhXxDjPos> mList) {
		// TODO Auto-generated method stub

	}

}
